﻿using System;
using System.Globalization;
using System.Windows.Forms;

namespace Compiler.LabForms
{
    public partial class IdEdit : Form
    {
        private ListView _idsView;
        private ListViewItem _item;

        public IdEdit(ListView idsView)
        {
            _idsView = idsView;
            InitializeComponent();
            Text = @"Добавление идентификатора";
            typeBox.SelectedIndex = 0;
            levelBox.SelectedIndex = 0;
        }

        public IdEdit(ListView idsView, ListViewItem item)
        {
            _idsView = idsView;
            _item = item;
            InitializeComponent();
            Text = @"Редактирование идентификатора";
            valueBox.Text = _item.SubItems[1].Text;
            typeBox.SelectedIndex = GetTypeIdByText(_item.SubItems[2].Text);
            levelBox.SelectedIndex = GetLevelIdByText(_item.SubItems[3].Text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(valueBox.Text)) return;
            if (_item != null)
            {
                _item.SubItems[1].Text = valueBox.Text;
                _item.SubItems[2].Text = typeBox.Text;
                _item.SubItems[3].Text = levelBox.Text;
            }
            else
            {
                var newItem = new ListViewItem
                {
                    Text = Lab.IdentifierId.ToString(CultureInfo.InvariantCulture),
                };
                newItem.SubItems.Add(valueBox.Text);
                newItem.SubItems.Add(typeBox.Text);
                newItem.SubItems.Add(levelBox.Text);
                _idsView.Items.Add(newItem);
                Lab.IdentifierId++;
            }
            _idsView.SelectedItems.Clear();
            Close();
        }

        private int GetTypeIdByText(string text)
        {
            switch (text)
            {
                case "void":
                    return 0;
                case "int":
                    return 1;
                case "bool":
                    return 2;
                default:
                    return -1;
            }
        }

        private int GetLevelIdByText(string text)
        {
            switch (text)
            {
                case "Глобальный":
                    return 0;
                case "Локальный":
                    return 1;
                default:
                    return -1;
            }
        }
    }
}
